package com.gbq.task;

import com.gbq.constants.BaseConstants;
import com.gbq.service.BaseService;
import com.gbq.utils.BaseUtils;
import com.gbq.vo.Device;
import com.gbq.vo.ResultVo;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.*;

import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;


import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Component
@Slf4j
public class Task {

    private static final Gson gson=new GsonBuilder().disableHtmlEscaping().create();



    @Autowired
    private BaseService baseService;

    @Autowired
    private RestTemplate restTemplate;

    @Value("${kafkaPersonIP}")
    private String kafkaPersonIP;

    @Value("${kafkaPictureIP}")
    private String kafkaPictureIP;


    //每隔30s检查一次设备在线
    @Scheduled(cron="0 0/5 *  * * ? ")
    public void ping() {

        log.info("==================开始心跳检查=========================");
        BaseConstants.count++;
        List<Device> lists = null;
        try {
            lists = baseService.select();
        } catch (Exception e) {
            log.info(gson.toJson(new ResultVo(ResultVo.ERROR,e.getMessage())));
        }

        lists.stream().forEach(list->{

            String line = null;
            Boolean isOnline = true;
            Integer lineCount = 1;
            log.info("ping "+list.getIp()+" -c 4");

            try {
                Process pro = Runtime.getRuntime().exec("ping "+list.getIp()+"  -c 4");
                BufferedReader buf = new BufferedReader(new InputStreamReader(pro.getInputStream(),"UTF-8"));
                while (((line = buf.readLine()) != null)&&lineCount<4)  {
                    System.out.println(line.toLowerCase());
                    isOnline = BaseUtils.strIndexOf(line.toLowerCase(),"ttl");
                    lineCount++;
                }

            } catch (IOException e) {
                log.info(gson.toJson(new ResultVo(ResultVo.ERROR,e.getMessage())));
                isOnline = false;
            }
            log.info(isOnline.toString());
            if (isOnline){
                baseService.updateDeviceStatus("online",list.getSn(),new Date());
            }else {
                baseService.updateDeviceStatus("offline",list.getSn(),new Date());
            }

        });
        log.info("==================心跳检查结束=========================");
    }

    public Boolean postPersonList(Map<String,Object> map){

        String result = null;
        try {
            result = restTemplate.postForObject(kafkaPersonIP, map, String.class);
            return true;
        } catch (RestClientException e) {
            log.info(e.toString());
            return false;
        }

    }




    private HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() {
        @Override
        public boolean retryRequest(IOException exception,
                                    int executionCount, HttpContext context) {
            return false;
        }};

    public Boolean postPicture(String pathName){

//        HttpClient httpclient = new DefaultHttpClient();
        HttpClient httpclient = HttpClients.custom().setRetryHandler(myRetryHandler).build();
        try {
            //新建一个httpclient Post 请求
            //URI是服务地址，需要填实际的ip
            HttpPost httppost = new HttpPost(kafkaPictureIP);

            //需要上传的文件
            File myfile = new File(pathName);

            String fileName = myfile.getName();
            System.out.println("filename:" + fileName);
            FileBody bin = new FileBody(myfile, ContentType.DEFAULT_BINARY,fileName);

            long size  = myfile.length();
            //向MultipartEntity添加必要的数据

            MultipartEntity reqEntity = new MultipartEntity();
            reqEntity.addPart("file",bin);//file为请求后台的Fileupload参数

            httppost.setEntity(reqEntity);
            //这里是后台接收文件的接口需要的参数，根据接口文档需要放在http请求的请求头
            String taskid ="919894d9-ea5a-4f6a-8edd-b14ef3b6f104";
            httppost.setHeader("task-id",taskid);
//            String fileid = UUID.randomUUID().toString();
//            httppost.setHeader("file-id",fileid);
            httppost.setHeader("file-name",fileName);
            httppost.setHeader("file-size",String.valueOf(size));
            httppost.setHeader("total", String.valueOf(1));
            httppost.setHeader("index",String.valueOf(1));

            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(3000).setConnectionRequestTimeout(1000)
                    .setSocketTimeout(3000).build();// 设置请求和传输超时时间
            httppost.setConfig(requestConfig);

            HttpResponse response = httpclient.execute(httppost);
            int statusCode = response.getStatusLine().getStatusCode();
            System.out.println(statusCode);
            if(statusCode == 200){
                System.out.println("服务器正常响应.....");
                HttpEntity resEntity = response.getEntity();
                System.out.println(EntityUtils.toString(resEntity));
                System.out.println(resEntity.getContent());
                EntityUtils.consume( resEntity);
            }
            return true;
        } catch (ParseException e) {
            log.info(e.toString());
            return false;
        } catch (IOException e) {
            if (e.toString().indexOf("timed out")!=-1){
                log.info(e.toString());
            }else {
                log.info("文件传输完毕");
            }
            return false;
        } finally {
            try {
                httpclient.getConnectionManager().shutdown();
            } catch (Exception ignore) {
            }
        }
    }


}
